package nc.bs.fileupload.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.swing.tree.TreeNode;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import nc.bs.fileupload.itf.IBipFileUploadService;
import nc.bs.framework.common.NCLocator;
import nc.bs.pub.filesystem.IFileSystemService;
import nc.bs.pub.filesystem.IQueryFolderTreeNodeService;
import nc.itf.pub.dbservice.IDBService;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.BusinessException;
import nc.vo.pub.filesystem.FileTypeConst;
import nc.vo.pub.filesystem.NCFileNode;
import nc.vo.pub.filesystem.NCFileVO;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pubapp.AppContext;
import nccloud.bs.fileupload.AttachmentFileUploadUtil;
import nccloud.bs.log.ImplLogVO;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.SessionContext;
import nccloud.pubitf.platform.attachment.IAttachmentService;
import nccloud.pubitf.platform.attachment.IFileStorageConst;
import nccloud.web.platform.attachment.action.WebFileParaConvertor;
import uap.pub.fs.domain.basic.FileHeader;

public class BipFileUploadServiceImpl implements IBipFileUploadService {
	private IQueryFolderTreeNodeService queryFolderTreeNodeService;
	private IFileSystemService fileSystemService;
	private IAttachmentService attachmentService;
	private IDBService dbService;

	@Override
	public void createAttNode(String folderName, String parentPath, String userid)
			throws BusinessException {
		IFileSystemService fservice = NCLocator.getInstance().lookup(IFileSystemService.class);
		fservice.createNewFileNode(parentPath, folderName,userid);
	}

	@Override
	public void fileUpload(String fullPath,String billID, String vbillcode, List<String> fileURLs, String pk_group,
						   String pk_org,String pk_org_v, String pk_billtypeid,String cuserid) throws BusinessException {

		List<String> filePaths = new ArrayList<String>();
		if (fileURLs == null || fileURLs.isEmpty())
			return; // 需要上传的附件为空
		String newBucket = getStorePath(null);
		List<ImplLogVO> succvos = new ArrayList<ImplLogVO>();
		List<ImplLogVO> errorvos = new ArrayList<ImplLogVO>();
		for (String obj : fileURLs) {
			JSONObject json = JSON.parseObject(obj);
			String fileURL = json.getString("url");
			// 特殊字符转义
			String attachmentName = json.getString("filename").replaceAll("[<>:\"/\\\\|?*]", "_");
            ImplLogVO logvo  = AttachmentFileUploadUtil.setDefaultLogVO(fileURL, pk_group, pk_org, pk_org_v, pk_billtypeid);
			URL url = null;
			URLConnection conn = null;
			InputStream inputStream = null;
			try {
				try {
					url = new URL(fileURL);
					conn = url.openConnection();
					inputStream = conn.getInputStream();
				}catch(Exception e) {
					throw new Exception("附件地址["+fileURL+"]不合理, 异常信息:" + e.getMessage());
				}
				FileHeader header = getAttachmentService().upload(attachmentName, inputStream, false, 0, newBucket);
				saveDBInfo(fullPath, header,cuserid);
				filePaths.add(fullPath + "/" + header.getName());
				logvo.setError("附件下载成功");
				logvo.setIssuccess("Y");
				succvos.add(logvo);
			} catch (Exception e) {
				logvo.setError("附件保存数据库异常:" + e.getMessage());
				logvo.setIssuccess("N");
				errorvos.add(logvo);
				throw new BusinessException(e);
			}finally {
				if(inputStream != null ) {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		if(succvos != null  && !succvos.isEmpty()) {
			getDbService().insertVOList(succvos);
		}
		if(errorvos != null && !errorvos.isEmpty()) {
			getDbService().insertVOList(errorvos);
		}

	}

	@Override
	public void fileUploadURL(String fullPath, String billID, String vbillcode, List<String> fileURLs, String pk_group, String pk_org, String pk_org_v, String pk_billtypeid, String cuserid) throws BusinessException {
		List<String> filePaths = new ArrayList<String>();
		if (fileURLs == null || fileURLs.isEmpty())
			return; // 需要上传的附件为空
		List<ImplLogVO> succvos = new ArrayList<ImplLogVO>();
		List<ImplLogVO> errorvos = new ArrayList<ImplLogVO>();
		for (String obj : fileURLs) {
			JSONObject json = JSON.parseObject(obj);
			String fileURL = json.getString("url");
			// 特殊字符转义
			String attachmentName = json.getString("filename").replaceAll("[<>:\"/\\\\|?*]", "_");
			ImplLogVO logvo  = AttachmentFileUploadUtil.setDefaultLogVO(fileURL, pk_group, pk_org, pk_org_v, pk_billtypeid);
			try {
				NCFileVO newfilevo = new NCFileVO();
				newfilevo.setCreator(cuserid);
				newfilevo.setPath(fullPath + "/" + attachmentName+".url"); // 默认格式 文件名.url
				newfilevo.setFolder(false);
				newfilevo.setFiletype(FileTypeConst.URL);
				newfilevo.setTime((new Date()).getTime());
				newfilevo.setDirty(UFBoolean.FALSE.isValue());
				newfilevo.setFileLen(0);
				newfilevo.setPk_doc(fileURL);
				this.getFileSystemService().insertURLFileVO(newfilevo);
				this.getAttachmentService().saveFileLog(fullPath, newfilevo);
			} catch (Exception e) {
				logvo.setError("附件保存数据库异常:" + e.getMessage());
				logvo.setIssuccess("N");
				errorvos.add(logvo);
				throw new BusinessException(e);
			}
		}
		if(succvos != null  && !succvos.isEmpty()) {
			getDbService().insertVOList(succvos);
		}
		if(errorvos != null && !errorvos.isEmpty()) {
			getDbService().insertVOList(errorvos);
		}
	}

	@Override
	public void fileUploadNC(String fullPath, String billID, String vbillcode, List<String> fileURLs, String pk_group,
							 String pk_org, String pk_org_v, String pk_billtypeid, String cuserid) throws BusinessException {

		List<String> filePaths = new ArrayList<String>();
		if (fileURLs == null || fileURLs.isEmpty())
			return; // 需要上传的附件为空
		String newBucket = getStorePath(null);
		List<ImplLogVO> succvos = new ArrayList<ImplLogVO>();
		List<ImplLogVO> errorvos = new ArrayList<ImplLogVO>();
		for (String obj : fileURLs) {
			JSONObject json = JSON.parseObject(obj);
			String fileURL = json.getString("attachmentPath");
			String type = json.getString("attachmentType");
			String name = json.getString("attachmentName");
			
			String attname =  name+"."+ type;
			// 特殊字符转义
			String attachmentName = attname.replaceAll("[<>:\"/\\\\|?*]", "_");
			ImplLogVO logvo  = AttachmentFileUploadUtil.setDefaultLogVO(fileURL, pk_group, pk_org, pk_org_v, pk_billtypeid);
			URL url = null;
			URLConnection conn = null;
			InputStream inputStream = null;
			try {
				try {
					url = new URL(fileURL);
					conn = url.openConnection();
					inputStream = conn.getInputStream();
				}catch(Exception e) {
					throw new Exception("附件地址["+fileURL+"]不合理, 异常信息:" + e.getMessage());
				}
				FileHeader header = getAttachmentService().upload(attachmentName, inputStream, false, 0, newBucket);
				saveDBInfo(fullPath, header,cuserid);
				filePaths.add(fullPath + "/" + header.getName());
				logvo.setError("附件下载成功");
				logvo.setIssuccess("Y");
				succvos.add(logvo);
			} catch (Exception e) {
				logvo.setError("附件保存数据库异常:" + e.getMessage());
				logvo.setIssuccess("N");
				errorvos.add(logvo);
				throw new BusinessException(e);
			}finally {
				if(inputStream != null ) {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		if(succvos != null  && !succvos.isEmpty()) {
			getDbService().insertVOList(succvos);
		}
		if(errorvos != null && !errorvos.isEmpty()) {
			getDbService().insertVOList(errorvos);
		}



	}

	private String getStorePath(String[] storepaths) {
		String storepath = IFileStorageConst.Bucket;
		if (storepaths != null && storepaths.length > 0 && storepaths[0] != null && !"".equals(storepaths[0])) {
			storepath = storepaths[0];
		}
		return storepath;
	}

	private NCFileNode saveDBInfo(String fullPath, FileHeader header,String cuserid) {
		IAttachmentService ncservice = NCLocator.getInstance().lookup(IAttachmentService.class);
		NCFileVO attach = new NCFileVO();
		attach.setPath(header.getName());
		attach.setCreator(cuserid);
		attach.setFileLen(header.getFileSize().longValue());
		attach.setPk_doc(header.getPath());
		attach.setIsdoc("z");
		return ncservice.saveAttachDBInfo(fullPath, attach);
	}

	private boolean CheckTheSameFileName(TreeNode node, String filename) {
		for (int noden = 0; noden < node.getChildCount(); noden++) {
			TreeNode subnode = node.getChildAt(noden);
			if (filename.trim().equalsIgnoreCase(subnode.toString().trim())) {
				return true;
			}
		}
		return false;
	}

	public IQueryFolderTreeNodeService getQueryFolderTreeNodeService() {
		if (queryFolderTreeNodeService == null) {
			queryFolderTreeNodeService = NCLocator.getInstance().lookup(IQueryFolderTreeNodeService.class);
		}
		return queryFolderTreeNodeService;
	}

	public IFileSystemService getFileSystemService() {
		if (fileSystemService == null) {
			fileSystemService = NCLocator.getInstance().lookup(IFileSystemService.class);
		}
		return fileSystemService;
	}

	public IAttachmentService getAttachmentService() {
		if (attachmentService == null) {
			attachmentService = NCLocator.getInstance().lookup(IAttachmentService.class);
		}
		return attachmentService;
	}

	public IDBService getDbService() {
		if (dbService == null) {
			dbService = NCLocator.getInstance().lookup(IDBService.class);
		}
		return dbService;
	}
}
